import 'dart:io';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/channel_apis.dart';
import 'package:flutter_syt/datas/index_setting.dart';
import 'package:flutter_syt/datas/provider_background.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/domain/games/games_page.dart';
import 'package:flutter_syt/domain/home/home_page.dart';
import 'package:flutter_syt/domain/mine/mine_page.dart';
import 'package:flutter_syt/domain/mine/service/provider_unread_msg.dart';
import 'package:flutter_syt/domain/test/test_page.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import 'news/news_page.dart';

enum TabType { HOME, NEWS, GAMES, CHENGDU, MINE, DEBUG }

class _TabEntity {
  late String icon;
  late String activeIcon;
  late String label;
  late Widget widget;
  late TabType tabType;

  _TabEntity();

  factory _TabEntity.create(String icon, String activeIcon, String label,
      TabType tabType, Widget widget) {
    return _TabEntity()
      ..icon = icon
      ..activeIcon = activeIcon
      ..label = label
      ..tabType = tabType
      ..widget = widget;
  }
}

@RoutePage(name: "mainPage")
class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

int kTCurrentTabIndex = 0;
EdgeInsets kCurrentAppSafeInset = EdgeInsets.zero;

class _MainPageState extends State<MainPage>
    with RouteAware, WidgetsBindingObserver {
  List<_TabEntity> _tab = [];
  int? _gameSchedule;
  // @override
  // void didPopNext() {
  //   // OnlineGlobalData.shared.update();
  //   super.didPopNext();
  // }

  var isDispose = false;
  @override
  void dispose() {
    appContext.rootObserver.unsubscribe(this);
    isDispose = true;
    // WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   // print("-didChangeAppLifecycleState-" + state.toString());
  //   DLog("-didChangeAppLifecycleState-" + state.toString());
  //   switch (state) {
  //     case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
  //       DLog('于这种状态的应用程序应该假设它们可');
  //       JPush().setBadge(0);
  //       // ProviderBackground provider =
  //       //     Provider.of<ProviderBackground>(appContext.context!, listen: false);
  //       // provider.setIsShowFilter(true);
  //       break;
  //     case AppLifecycleState.resumed: //从后台切换前台，界面可见
  //       DLog('从后台切换前台，界面可见');
  //       // ProviderBackground provider =
  //       //     Provider.of<ProviderBackground>(appContext.context!, listen: false);
  //       // provider.setIsShowFilter(false);
  //       // JPush().setBadge(0);
  //       break;
  //     case AppLifecycleState.paused: // 界面不可见，后台
  //       DLog('界面不可见，后台');
  //       break;
  //     case AppLifecycleState.detached: // APP结束时调用
  //       DLog('APP结束时调用');
  //       break;
  //   }
  // }

  @override
  void didChangeDependencies() {
    var route = ModalRoute.of<dynamic>(context);
    if (route != null) {
      appContext.rootObserver.subscribe(this, route);
    }
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
    // OnlineGlobalData.shared.addListener(() {
    //   if (!isDispose) {
    //     setState(() {});
    //   }
    // });


    API.shared.common.indexSetting().then((IndexSetting setting) {
      ProviderIndexSetting indexSettingProvider =
          Provider.of<ProviderIndexSetting>(context, listen: false);
      indexSettingProvider.indexSetting = setting;
      if (setting.globalStop == 1) {
        showStopServiceDialog(context, isStop: true);
      } else if (setting.globalPause == 1) {
        showStopServiceDialog(context, isStop: false);
      }
    });
    try {
      API.shared.user.agreementsV2(6).then((value) {
        DLog(value);
        appContext.permissionData = value;
      });
      // CAMERA
    } catch (e) {
      DLog(e);
    }
    // getProtocolInfo

    // OnlineGlobalData.shared.update();
    VersionUpdate.update(context, false);
    // ThirdSDKAPI
    if (Platform.isAndroid) {
      appContext.channelApi.getRegistrationID();

      // appContext.channelApi.apkVerifyWithSHA();
    }
    // WidgetsBinding.instance.addObserver(this);
    // }
  }

  creatTab(ProviderIndexSetting providerIndexSetting) {
    // if (kDebugMode) {
    //   providerIndexSetting.indexSetting.gameSchedule = 1;
    // }
    _tab = [
      _TabEntity.create(
        "assets/icons/icon_tab_home.png",
        "assets/icons/icon_tab_active_home.png",
        S.of(context).home, //首页
        TabType.HOME,
        HomePage(),
      ),
      _TabEntity.create(
        "assets/icons/icon_tab_news.png",
        "assets/icons/icon_tab_active_news.png",
        S.of(context).home_news, //资讯
        TabType.NEWS,
        NewsPageNotChengdu(),
      ),
      if (providerIndexSetting.indexSetting.gameSchedule == 1)
        _TabEntity.create(
          "assets/icons/icon_tab_games.png",
          "assets/icons/icon_tab_active_games.png",
          S.of(context).competitions, //赛程
          TabType.GAMES,
          GamesPage(),
        ),
      _TabEntity.create(
        "assets/icons/icon_tab_chengdu.png",
        "assets/icons/icon_tab_active_chengdu.png",
        S.of(context).chengdu, //成都
        TabType.CHENGDU,
        NewsPage(),
      ),
      _TabEntity.create(
        "assets/icons/icon_tab_mine.png",
        "assets/icons/icon_tab_active_mine.png",
        S.of(context).my_account, //我的
        TabType.MINE,
        MinePage(),
      ),
      if (appContext.isDebugMode)
        _TabEntity.create(
          "assets/icons/icon_tab_mine.png",
          "assets/icons/icon_tab_active_mine.png",
          "Debug",
          TabType.DEBUG,
          TestPage(),
        ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    kCurrentAppSafeInset = MediaQuery.of(context).padding;
    appContext.context = context;
    return Consumer2<ProviderIndexSetting, ProviderBackground>(
      builder: (context, value, background, child) {
        if (_gameSchedule == null ||
            _gameSchedule != value.indexSetting.gameSchedule) {
          creatTab(value);
          _gameSchedule = value.indexSetting.gameSchedule;
        }

        return Scaffold(
          body: IndexedStack(
            children: _tab.map((e) => e.widget).toList(),
            index: kTCurrentTabIndex,
          ),
          // body: _tab[kTCurrentTabIndex].widget,
          bottomNavigationBar: Theme(
            data: ThemeData(
              brightness: Brightness.light,
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
            ),
            child: BottomNavigationBar(
              unselectedFontSize: 12,
              selectedFontSize: 12,
              unselectedItemColor: const Color(0xFFCDCDCD),
              selectedItemColor: const Color(0xFF000000),
              type: BottomNavigationBarType.fixed,
              items: _tab.map((e) {
                return BottomNavigationBarItem(
                  icon: e.label == S.of(context).my_account
                      ? _buildRed(Image.asset(
                          e.icon,
                          width: 24,
                          height: 24,
                        ))
                      : Image.asset(
                          e.icon,
                          width: 24,
                          height: 24,
                        ),
                  activeIcon: e.label == S.of(context).my_account
                      ? _buildRed(Image.asset(
                          e.activeIcon,
                          width: 24,
                          height: 24,
                        ))
                      : Image.asset(
                          e.activeIcon,
                          width: 24,
                          height: 24,
                        ),
                  label: e.label,
                );
              }).toList(),
              currentIndex: kTCurrentTabIndex,
              onTap: (idx) async {
                if (mounted) {
                  setState(() {
                    kTCurrentTabIndex = idx;
                  });
                }
                ProviderIndexSetting indexSettingProvider =
                    Provider.of<ProviderIndexSetting>(appContext.context!,
                        listen: false);
                if (indexSettingProvider.isLoad == false) {
                  await GlobalData.getIndexSetting();
                  if (mounted) {
                    setState(() {
                      kTCurrentTabIndex = 0;
                    });
                  }
                }
              },
            ),
          ),
        );
      },
    );
  }

  Widget _buildRed(Widget childItem) {
    return Consumer<ProviderUnReadMsg>(
      builder: (context, value, child) {
        return Container(
            width: 24,
            height: 24,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Center(child: childItem),
                ),
                Positioned(
                    top: 0,
                    right: 0,
                    child: Visibility(
                        visible: value.unReadNum > 0 &&
                            ProviderIndexSetting().indexSetting.service == 1,
                        child: Container(
                            width: 8,
                            height: 8,
                            decoration: BoxDecoration(
                                color: Color(0xffEA2121),
                                borderRadius: BorderRadius.circular(4)))))
              ],
            ));
        // return child;
      },
    );
  }
}
